package com.bit.net;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 控制中心服务初始化客户端连接.
 *
 * @since 2018/10/10
 */

@Slf4j
public abstract class BaseChannelInitializer extends ChannelInitializer<SocketChannel> {


    /**
     * 模块消息注册模块
     */
    private EachModulModelMessages modelMessages = new EachModulModelMessages();

    /**
     * 初始化消息类型模块
     */
    public BaseChannelInitializer() {
        registerModuleMessage(modelMessages);
    }

    /**
     * 给编解码器注册消息
     * @param modulModelMessages
     */
    protected abstract void registerModuleMessage(EachModulModelMessages modulModelMessages);

    protected abstract SimpleChannelInboundHandler getBizHandler();


    @Override
    protected void initChannel(final SocketChannel ch) throws Exception {
        log.info("client : {} connected.", ch.remoteAddress());
        ch.pipeline().addLast(new RequestDecoder(modelMessages));
        ch.pipeline().addLast(new ResponseEncoder(modelMessages));
        ch.pipeline().addLast(new ReadTimeoutHandler(1000, TimeUnit.SECONDS));
        ch.pipeline().addLast(getBizHandler());
    }

}
